package com.sgb.kjwl.viewmodel.transport;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.text.TextUtils;

import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.MutableLiveData;

import com.google.gson.reflect.TypeToken;
import com.sgb.kjwl.api.GsonManager;
import com.sgb.kjwl.api.NewAPIManager;
import com.sgb.kjwl.model.entity.ProListEntity;
import com.sgb.kjwl.model.entity.lease.CompanyInfoEntity;
import com.sgb.kjwl.model.entity.transport.CarFilterEntity;
import com.sgb.kjwl.model.entity.transport.CarHallEntity;
import com.sgb.kjwl.model.entity.transport.FilterTabEntity;
import com.sgb.kjwl.model.entity.transport.GoodsInfoTypeEntity3;
import com.sgb.kjwl.model.entity.transport.GoodsSourceLocationEntity;
import com.sgb.kjwl.model.entity.transport.MapCarPositionEntity;
import com.sgb.kjwl.model.entity.user.AddressEntity;
import com.sgb.kjwl.utils.AddressHelper;
import com.sgb.kjwl.utils.LocationUtil;
import com.sgb.kjwl.utils.NumberUtil;
import com.sgb.member.entity.QualityMemberBean;
import com.sgb.member.ui.activity.MemberInviteJoinActivity;
import com.sgb.member.ui.activity.PersonInviteJoinActivity;
import com.swgk.core.base.api.ICallBack;
import com.swgk.core.base.model.entity.BaseEntity;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SharedPreferenceUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class CarsModel extends AndroidViewModel {
    public MutableLiveData<List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>>> ldAddress = new MutableLiveData<>();
    public MutableLiveData<MapCarPositionEntity> ldPosition = new MutableLiveData<>();
    public MutableLiveData<List<GoodsInfoTypeEntity3>> ldCarLen = new MutableLiveData<>();
    public MutableLiveData<List<GoodsInfoTypeEntity3>> ldCarType = new MutableLiveData<>();
    public MutableLiveData<List<GoodsInfoTypeEntity3>> ldCarFunction = new MutableLiveData<>();
    public MutableLiveData<CarFilterEntity> ldFilter = new MutableLiveData<>();
    public MutableLiveData<ProListEntity<List<CarHallEntity>>> ldCars = new MutableLiveData<>();
    public MutableLiveData<String> statusLiveData = new MutableLiveData<>();

    public String websiteNo;//主页身份no
    public String websiteType;//主页身份(个人、企业、团队)
    // 一级联动数据
    private final List<AddressEntity> mProvinceList = new ArrayList<>();
    // 二级联动数据
    private final List<List<AddressEntity>> mCityList = new ArrayList<>();
    // 三级联动数据
    private final List<List<List<AddressEntity>>> mDistrictList = new ArrayList<>();
    //是否是车辆大厅
    private boolean mIsCarHall = true;
    private Context mContext;

    public CarsModel(Application application) {
        super(application);
        mContext = application.getApplicationContext();
        ldFilter.setValue(new CarFilterEntity());
    }

    /**
     * 设置当前页面是否是车辆大厅
     */
    public void setIsCarHall(boolean isCarHall) {
        this.mIsCarHall = isCarHall;
    }

    /**
     * 初始化筛选tab
     */
    public void initFilterTab(List<FilterTabEntity> list) {
        if (list == null) return;
        list.clear();
        list.add(new FilterTabEntity("车辆位置", 0));
        list.add(new FilterTabEntity("车长", 0));
        list.add(new FilterTabEntity("功能", 0));
        list.add(new FilterTabEntity("装车时间", 0));
    }

    /**
     * 获取省市区地址
     */
    public void getAddressModel(Context context) {
        DialogHelper.showProgressDialog(context, "数据加载中...");
        AddressHelper.getInstance().getAllArea(new AddressHelper.AddressCallBack() {
            @Override
            public void initialData(List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> data) {
                DialogHelper.dismissProgressDialog();
                if (data != null) {
                    ldAddress.postValue(data);
                    //todo 暂时没用（开局根据定位查找省市区时使用）
//                    initAddress(context, data);
                    //获取车辆信息
                    getCarTypeList();
                    //获取车辆列表
//                    getCarList(context, 1);
                    getCarToList(context,1);
                }
            }
        });
    }

    @SuppressWarnings({"rawtypes", "unchecked"})
    private void initAddress(Context context, List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> list) {
        //拷贝数据，保留原始数据
        String dataStr = GsonManager.getInstance().getGson().toJson(list);
        List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> data = GsonManager.getInstance().getGson().fromJson(dataStr, new TypeToken<List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>>>() {
        }.getType());
        //添加全国
        data.add(0, new AddressEntity("", "不限", "", "不限"));
        for (AddressEntity<List<AddressEntity<List<AddressEntity>>>> pro : data) {
            //一级列表
            mProvinceList.add(pro);
            //二级列表
            if (pro.getChildren() == null) {
                pro.setChildren(new ArrayList<>());
            }
            //添加全省
            if (pro.getChildren().size() > 1) {
                pro.getChildren().add(0, new AddressEntity("", "不限", "", "不限"));
            }
            List<AddressEntity> cityList = new ArrayList<>(pro.getChildren());
            mCityList.add(cityList);
            //三级列表
            List<List<AddressEntity>> areaList = new ArrayList<>();
            for (AddressEntity<List<AddressEntity>> area : pro.getChildren()) {
                if (area.getChildren() == null) {
                    area.setChildren(new ArrayList<>());
                }
                area.getChildren().add(0, new AddressEntity("", "不限", "", "不限"));
                areaList.add(area.getChildren());
            }
            mDistrictList.add(areaList);
        }
        //查找地址下标
        if (LocationUtil.isOpenLocation(context)) {
            String provinceName = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.Province, "新疆");
            findPositionByAddress(provinceName, "", "");
        } else {
            findPositionByAddress("新疆", "", "");
        }
    }

    /**
     * 获取车辆类型
     */
    public void getCarTypeList() {
        NewAPIManager.getInstance().getLogisticsAPI().getCarTypeAndLen("").enqueue(new ICallBack<BaseEntity<List<GoodsInfoTypeEntity3>>>() {
            @Override
            public void onSuccess(BaseEntity<List<GoodsInfoTypeEntity3>> data) {
                List<GoodsInfoTypeEntity3> carTypeList = data.getData() != null ? data.getData() : new ArrayList<>();
                List<GoodsInfoTypeEntity3> carLenList = new ArrayList<>();
                //添加全部车长数据
                for (GoodsInfoTypeEntity3 carType : carTypeList) {
                    if (carType.getCarLenList() == null) continue;
                    carLenList.addAll(carType.getCarLenList());
                }
                //添加车型不限时所有车长数据
                GoodsInfoTypeEntity3 type = new GoodsInfoTypeEntity3("", "不限");
                type.setCarLenList(carLenList);
                carTypeList.add(0, type);
                //添加子列表不限车长
                for (GoodsInfoTypeEntity3 carType : carTypeList) {
                    if (carType.getCarLenList() == null) {
                        carType.setCarLenList(new ArrayList<>());
                    }
                    GoodsInfoTypeEntity3 len = new GoodsInfoTypeEntity3("", "不限");
                    carType.getCarLenList().add(0, len);
                }
                //刷新车长与车型
                ldCarType.postValue(carTypeList);
                ldCarLen.postValue(carLenList);
            }
        });
    }

    /**
     * 获取车辆功能
     */
    public void getCarFunction() {
        NewAPIManager.getInstance().getLogisticsAPI().getCarFunction().enqueue(new ICallBack<BaseEntity<List<GoodsInfoTypeEntity3>>>() {
            @Override
            public void onSuccess(BaseEntity<List<GoodsInfoTypeEntity3>> data) {
                if (data.getData() == null) {
                    data.setData(new ArrayList<>());
                }
                data.getData().add(0, new GoodsInfoTypeEntity3("", "不限"));
                ldCarFunction.postValue(data.getData());
            }
        });
    }

    /**
     * 通过地址查找下标
     */
    private void findPositionByAddress(String provinceName, String cityName, String districtName) {
        //创建发货地数据
        if (ldFilter.getValue().getSend() == null) {
            ldFilter.getValue().setSend(new GoodsSourceLocationEntity());
        }
        //省市区弹窗选中位置
        int proPos = 0, cityPos = 0, disPos = 0;
        //针对特殊省处理
        if (!TextUtils.isEmpty(provinceName)) {
            if (provinceName.contains("台湾")) {
                //针对特殊省处理
                provinceName = "台湾";
            } else if (provinceName.endsWith("市")) {
                //针对直辖市处理(适应接口)
                provinceName = provinceName.substring(0, provinceName.length() - 1);
            }
        }
        //查找省position
        for (AddressEntity entity : mProvinceList) {
            if (entity.getName().contains(provinceName)) {
                ldFilter.getValue().getSend().setProvinceNo(entity.getNo());
                ldFilter.getValue().getSend().setProvinceName(entity.getSimpleName());
                proPos = mProvinceList.indexOf(entity);
                break;
            }
        }
        //查找市position
        List<AddressEntity> cityList = mCityList.get(proPos);
        for (AddressEntity entity : cityList) {
            if (entity.getName().contains(cityName)) {
                ldFilter.getValue().getSend().setCityNo(entity.getNo());
                ldFilter.getValue().getSend().setCityName(entity.getSimpleName());
                cityPos = cityList.indexOf(entity);
                break;
            }
        }
        //查找区position
        if (districtName.endsWith("市") || districtName.endsWith("县") || districtName.endsWith("区")) {
            districtName = districtName.substring(0, districtName.length() - 1);
        }
        if (mDistrictList != null && mDistrictList.get(proPos).size() > 0) {
            List<AddressEntity> districtList = mDistrictList.get(proPos).get(cityPos);
            for (AddressEntity entity : districtList) {
                if (entity.getName().contains(districtName)) {
                    ldFilter.getValue().getSend().setAreaNo(entity.getNo());
                    ldFilter.getValue().getSend().setAreaName(entity.getSimpleName());
                    disPos = districtList.indexOf(entity);
                    break;
                }
            }
        }
        ldPosition.postValue(new MapCarPositionEntity(proPos, cityPos, disPos));
    }

    /**
     * 为列表查找数据
     *
     * @param page
     */
    public void getCarToList(Context context,int page) {
        Map map = new HashMap();
        map.put("page", page);
        map.put("limit", 10);
        if (!TextUtils.isEmpty(websiteType) && !TextUtils.isEmpty(websiteNo)) {
            map.put("needVideo", 0);
            switch (websiteType) {
                case "0":
                    map.put("userNo",websiteNo);
                    break;
                case "1":
                    map.put("companyNo",websiteNo);
                    break;
                case "2":
                    map.put("teamNo",websiteNo);
                    break;
            }
        } else {
            map.put("needVideo", 1);
        }
        if (!TextUtils.isEmpty(websiteNo) && !TextUtils.isEmpty(websiteType)) {
            map.put("searchType",1);
        }

        if (LocationUtil.isOpenLocation(mContext) && LocationUtil.currentLocationIsValid()) {
            map.put("ipLongitude", NumberUtil.convertToDouble(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LONGITUDE_ID, "")));
            map.put("ipLatitude", NumberUtil.convertToDouble(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LATITUDE_ID, "")));
        }

        //当前查找经纬度
        map.put("searchLongitude", ldFilter.getValue().getLongitude());
        map.put("searchLatitude", ldFilter.getValue().getLatitude());

        if (ldFilter.getValue().getCarLen() != null) {
            map.put("carLenNos", ldFilter.getValue().getCarLen().getNo());
        } else {
            map.put("carLenNos", "");
        }

        if (ldFilter.getValue().getCarType() != null) {
            map.put("carTypeNos", ldFilter.getValue().getCarType().getNo());
        } else {
            map.put("carTypeNos", "");
        }

        if (ldFilter.getValue().getSend() != null) {
            if (!TextUtils.isEmpty(ldFilter.getValue().getSend().getProvinceNo())) {
                map.put("provinceNo", ldFilter.getValue().getSend().getProvinceNo());
            } else {
                map.put("provinceNo", "");
            }

            if (!TextUtils.isEmpty(ldFilter.getValue().getSend().getCityNo())) {
                map.put("cityNo", ldFilter.getValue().getSend().getCityNo());
            } else {
                map.put("cityNo", "");
            }

            if (!TextUtils.isEmpty(ldFilter.getValue().getSend().getAreaNo())) {
                map.put("districtNo", ldFilter.getValue().getSend().getAreaNo());
            } else {
                map.put("districtNo", "");
            }
        }

        if (ldFilter.getValue().getCarFunction() != null) {
            if (!TextUtils.isEmpty(ldFilter.getValue().getCarFunction().getNo())) {
                map.put("functionNos", ldFilter.getValue().getCarFunction().getNo());
            } else {
                map.put("functionNos", "");
            }
        }

        if (ldFilter.getValue().getShipmentTime() != 0) {
            map.put("shipmentTime", ldFilter.getValue().getShipmentTime());
        } else {
            map.put("shipmentTime", null);
        }

        if (ldFilter.getValue().getShipmentEndTime() != 0) {
            map.put("shipmentEndTime", ldFilter.getValue().getShipmentEndTime());
        } else {
            map.put("shipmentEndTime", null);
        }
        DialogHelper.showProgressDialog(context, null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(true);
        NewAPIManager.getInstance().getLogisticsAPI().getCarToMainPage(map).enqueue(new Callback<BaseEntity<ProListEntity<List<CarHallEntity>>>>() {
            @Override
            public void onResponse(Call<BaseEntity<ProListEntity<List<CarHallEntity>>>> call, Response<BaseEntity<ProListEntity<List<CarHallEntity>>>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null)
                    return;
                if (response.body().getData() == null || response.body().getData().getList()==null) {
                    ldCars.postValue(new ProListEntity<>());
                    MToast.showToast(mContext, "没有更多车源了");
                    return;
                }
                ldCars.postValue(response.body().getData());
            }

            @Override
            public void onFailure(Call<BaseEntity<ProListEntity<List<CarHallEntity>>>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
                ldCars.postValue(new ProListEntity<>());
                MToast.showToast(mContext, "没有更多车源了");
            }
        });

    }

    public void getProcessStatus(String companyNo, String approveType) {
        NewAPIManager.getInstance().getMaterialAPI().getProcessStatus(companyNo, approveType).enqueue(new ICallBack<BaseEntity<Object>>() {
            @Override
            public void onSuccess(BaseEntity<Object> data) {
                // "status": "1" //1 表示有审批 0 代表无审批
                String status = ((Map<String, String>) data.getData()).get("status");
                if (!TextUtils.isEmpty(status)) {
                    statusLiveData.postValue(status);
                }
            }
        });
    }


    public void toInviteCompany(Context context, String companyNo, int inviteTerminal) {
        DialogHelper.showProgressDialog(context, null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(true);
        NewAPIManager.getInstance().getLogisticsAPI().getCompanyDetail(companyNo).enqueue(new ICallBack<BaseEntity<CompanyInfoEntity>>() {
            @Override
            public void onSuccess(BaseEntity<CompanyInfoEntity> data) {
                DialogHelper.dismissProgressDialog();
                CompanyInfoEntity entity = data.getData();
                QualityMemberBean memberBean = new QualityMemberBean();
                memberBean.setCompanyId(entity.getId());
                memberBean.setCompanyNo(companyNo);
                memberBean.setCompanyName(entity.getName());
                memberBean.setAddress(entity.getAddress());
                if (inviteTerminal == 0) {
                    //邀请个人
                    memberBean.setNo(entity.getNo());
                    PersonInviteJoinActivity.start((Activity) context, memberBean, false);
                } else if (inviteTerminal == 1) {
                    //邀请企业
                    memberBean.setServiceType(entity.getServiceType());
                    memberBean.setServiceTypeName(entity.getServiceType());
                    memberBean.setProvinceNo(entity.getProvinceNo());
                    memberBean.setCityNo(entity.getCityNo());
                    memberBean.setDistrictNo(entity.getDistrictNo());
                    MemberInviteJoinActivity.start((Activity) context, memberBean);
                }
            }
        });
    }
}
